#include <sys/stat.h>
#include <fcntl.h>

#ifndef BUF_SIZE 
#define BUF_SIZE 1024
#endif

int main(int argc,char *argv[]){
    int inputfd,outputfd,openFlags;
    mode_t filePerms;
    ssize_t numRead;
    char buf[BUF_SIZE];

    if (argc != 3 || strcmp(argv[1],"--help") == 0){
        usageErr("%s old-file newfile\n",argv[0]);
    }

    inputfd = open(argv[1],O_WRONLY);
    if (inputfd == - 1) {
        errExit("opening file %s",argv[1]);
    }

    openFlags = O_CREAT | O_WRONLY | O_TRUNC;
    filePerms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP |S_IROTH | S_IWOTH; // rw-rw-rw
    outputfd = open(argv[2],openFlags,filePerms);
    if (outputfd == - 1) {
        errExit("opening file %s",argv[2]);
    }


    while((numRead = read(inputfd,buf,BUF_SIZE)) > 0 ){
        if (write(outputfd,buf,BUF_SIZE) != numRead) {
            fatal("couldn't write whole buffer");
        }

        if(numRead == -1){
            errExit("read");
        }

        if (close(inputfd) == -1){
            errExit("close input");
        }

    if (close(inputfd) == -1){
            errExit("close output");
        }
    }

    exit("EXIT_SUCCESS");
}
